import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, LessThan, MoreThan, Between } from 'typeorm';
import { Activity } from '../modules/activity/entities/activity.entity';

@Injectable()
export class ActivityReminderService {
  private readonly logger = new Logger(ActivityReminderService.name);

  constructor(
    @InjectRepository(Activity)
    private readonly activityRepository: Repository<Activity>,
  ) {}

  // 每5分钟检查一次即将开始的活动
  @Cron(CronExpression.EVERY_5_MINUTES)
  async checkUpcomingActivities() {
    try {
      const now = new Date();
      const thirtyMinutesLater = new Date(now.getTime() + 30 * 60 * 1000);

      // 查找30分钟内即将开始的活动
      const upcomingActivities = await this.activityRepository.find({
        where: {
          startTime: Between(now, thirtyMinutesLater),
        },
        relations: ['creator'],
      });

      for (const activity of upcomingActivities) {
        await this.sendReminder(activity);
      }

      this.logger.log(`Checked ${upcomingActivities.length} upcoming activities`);
    } catch (error) {
      this.logger.error('Failed to check upcoming activities:', error);
    }
  }

  // 每天早上9点检查当天的活动
  @Cron(CronExpression.EVERY_DAY_AT_9AM)
  async checkTodayActivities() {
    try {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const tomorrow = new Date(today);
      tomorrow.setDate(tomorrow.getDate() + 1);

      const todayActivities = await this.activityRepository.find({
        where: {
          startTime: Between(today, tomorrow),
        },
        relations: ['creator'],
      });

      for (const activity of todayActivities) {
        await this.sendDailyReminder(activity);
      }

      this.logger.log(`Sent daily reminders for ${todayActivities.length} activities`);
    } catch (error) {
      this.logger.error('Failed to send daily activity reminders:', error);
    }
  }

  private async sendReminder(activity: Activity) {
    // TODO: 实现具体的提醒发送逻辑
    // 1. 发送站内消息
    // 2. 推送通知
    // 3. 短信提醒（可选）
    this.logger.log(`Sending reminder for activity: ${activity.title}`);
  }

  private async sendDailyReminder(activity: Activity) {
    // TODO: 实现每日提醒逻辑
    this.logger.log(`Sending daily reminder for activity: ${activity.title}`);
  }
}
